package com.mapler.ui;

import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

/**
 *
 * @author none
 */
public class AccountAllUI extends JPanel {

    private static Logger log = Logger.getLogger(AddAccessUI.class);
    private String username;
    private String password;
    private String country;
    int count = 0;
    private JLabel message;
    private JCheckBox jcbTickAll;
    private JCheckBox jcbUntickAll;

    public AccountAllUI() {
        initComponents();
    }

    public AccountAllUI(String username, String password, String country) {
        this.username = username;
        this.password = password;
        this.country = country;
    }

    public void initComponents() {
        try {
            setLayout(new SpringLayout());
            message = new javax.swing.JLabel();
            message.setText("Message");
            add(message);

            jcbTickAll = new JCheckBox();
            jcbTickAll.setText("Select All");
            jcbTickAll.setName("JCBTickAll");
            jcbTickAll.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jcbUntickAll.setSelected(false);
                    updateAll(1);
                }
            });
            add(jcbTickAll);


            jcbUntickAll = new JCheckBox();
            jcbUntickAll.setText("Deselect All");
            jcbUntickAll.setName("JCBUntickAll");
            jcbUntickAll.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jcbTickAll.setSelected(false);
                    updateAll(0);
                }
            });
            add(jcbUntickAll);

            javax.swing.JLabel blank = new javax.swing.JLabel();
            blank.setText("");
            add(blank);

            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=account/getAccounts&username="
                    + this.username + "&password=" + this.password + "&working=-1";
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/Response/accounts/account");
                count = 0;
                int inc = 1;
                for (Node node : list) {
                    final JCheckBox check = new javax.swing.JCheckBox();
                    check.setName("JCBCLA_" + node.valueOf("id"));
                    String lPostDate = node.valueOf("last_posted_date");
                    check.setText(inc + "     :-" + node.valueOf("email") + "|" + node.valueOf("state") + "|" 
                            + getDateAsString(lPostDate) + "|" + node.valueOf("proxy"));
                    if (node.valueOf("working").equalsIgnoreCase("1")) {
                        check.setSelected(true);
                    } if (node.valueOf("working").equalsIgnoreCase("2")) {
                        check.setForeground(Color.red);
                    }
                    add(check);
                    check.addActionListener(new Action(node.valueOf("id"), check) {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            message.setText("");
                            update(this.getId(), this.getjCheckBox().isSelected());
                        }
                    });
                    count++;
                    inc++;
                }
            } else {
                String msg = document.valueOf("Response/message");
                message.setText(msg);
            }
        } catch (Throwable ex) {
            log.debug("Error " + ex);
            ex.printStackTrace();
        }

        //Lay out the panel.
        SpringUtilities.makeCompactGrid(this,
                count + 4, 1, //rows, cols
                6, 6, //initX, initY
                6, 6);       //xPad, yPad
    }

    private String getDateAsString(String d) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
            String formattedDate = dateFormat.format(formatter.parse(d)).toString();
            
            return formattedDate;
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(AccountAllUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public void updateAll(int working) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(this.username).append("</username>");
            request.append("<password>").append(this.password).append("</password>");
            request.append("<country>").append(this.country).append("</country>");
            request.append("<working>").append(working).append("</working>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=account/updateAllWorking";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            if (errorCode.equalsIgnoreCase("000")) {
                message.setBackground(Color.red);
            } else {
                this.removeAll();
                this.initComponents();
            }
            message.setText(msg);
        } catch (Throwable ex) {
            message.setText("updateAll : Error on select " + ex.getMessage());
            log.debug("updateAll: Error " + ex);
        } finally {
        }
    }

    public void XupdateAll() {
        try {
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=account/getAccounts&username="
                    + this.username + "&password=" + this.password + "&working=0";
            String response = HttpHelper.post(new URL(uri), "");
            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            if (!errorCode.equalsIgnoreCase("000")) {
                List<Node> list = document.selectNodes("/Response/accounts/account");
                //for (Node node : list) {
                Component[] components = this.getComponents();
                for (int i = 0; i < components.length; i++) {
                    Component component = components[i];
                    if (component instanceof JCheckBox && component.getName() != null && component.getName().contains("JCBCLA")) {
                        JCheckBox cb = (JCheckBox) component;
                        cb.setSelected(!jcbTickAll.isSelected());
                        //cb.setSelected(jcbTickAll.isSelected());
                        cb.doClick();
                    }
                }
                //this.update(node.valueOf("id"), jcbTickAll.isSelected());
                //}
            } else {
                String msg = document.valueOf("Response/message");
                message.setText(msg);
            }
        } catch (Throwable ex) {
            message.setText("updateAll : Error on select " + ex.getMessage());
            log.debug("updateAll: Error " + ex);
        } finally {
        }
    }

    private void update(String id, boolean checked) {
        try {
            int work = 0;
            if (checked) {
                work = 1;
            }
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(this.username).append("</username>");
            request.append("<password>").append(this.password).append("</password>");
            request.append("<country>").append(this.country).append("</country>");
            request.append("<id>").append(id).append("</id>");
            request.append("<working>").append(work).append("</working>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=account/updateWorking";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            if (errorCode.equalsIgnoreCase("000")) {
                message.setBackground(Color.red);
            } else {
                this.message.setBackground(Color.black);
            }
            this.message.setText(msg);
        } catch (Throwable ex) {
            message.setText("update: Error on select " + ex.getMessage());
            log.debug("update: Error " + ex);
        }
    }
}
